var request = require('request');
var fs = require('fs');
var Promise = require('bluebird')
var configFileName = '/etc/simple_monitor.json';
var dft = {
	url: 'http://monitor.pandabtc.cn:2345/monitor/report',
	api_code: '',
	region: '',
	server: '',
	debug: false,
};

if(fs.existsSync(configFileName)) {
	var t = fs.readFileSync(configFileName).toString();
	try {
		t = JSON.parse(t);
		if(t) {
			dft = Object.assign({}, dft, t);
		}
	} catch(err) {
	}
}

module.exports = function (options) {
	options = Object.assign({
		process: 'unknown',
		type: 'unknown',
		version: '0',
	}, dft, options);

	return function () {

		if(!options.url || !options.api_code || !options.region || !options.server) {
			console.error('no simple_monitor url/api_code/region/server specified');
			return;
		}

		var values = [];
		for(var i = 0;i < arguments.length - 1;i++) {
			var k = arguments[i];
			var v = arguments[i + 1];
			k = String(k).replace(/,/g, '.');
			v = String(v).replace(/,/g, '.');
			values.push(k);
			values.push(v);
		}
		if(values.length == 0) return;

		var value = values.join(',');

		var params = {
			api_code: options.api_code,
			region: options.region,
			server: options.server,
			process: options.process,
			type: options.type,
			value: value,
			version: options.version,
		};

		var paramsInList = Object.keys(params).map(function(k) {
			return k + '=' + encodeURIComponent(params[k]);
		});

		var url = options.url + '?' + paramsInList.join('&');

		if(options.use_promise) {
			return new Promise(function(resolve, reject) {
				request({
					method: 'GET',
					uri: url,
					timeout: 30 * 1000,
				}, function(err, resp) {
//                request(url, function(err, resp) {
                    if(err) {
                        if (options.debug) {
                            console.error('simple_monitor', Date(), err);
                        }
                        reject();
                        return;
                    }
                    if(options.debug) {
                        console.log('simple_monitor', Date(), resp.body);
                    }
                    resolve();
                });
			})
		} else {
			request({
				method: 'GET',
				uri: url,
				timeout: 30 * 1000,
			}, function(err, resp) {
//			request(url, function(err, resp) {
				if(!options.debug) return;

				if(err) {
					console.error('simple_monitor', Date(), err);
					return;
				}

				console.log('simple_monitor', Date(), resp.body);
			});
		}

	}
}

